package com.bac.rentmap.web.controller.ad.add;

import java.io.PrintWriter;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.bac.rentmap.ad.flat.image.FlatImage;
import com.bac.rentmap.ad.flat.image.FlatImageService;
import com.bac.rentmap.ad.flat.image.FlatImageType;
import com.bac.rentmap.ad.flat.image.UnsupportedImageTypeException;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;

public class UploadFlatImageController extends MultiActionController {
    private static final Logger log = Logger
            .getLogger(UploadFlatImageController.class.getName());
    protected FlatImageService flatImageService;
    protected BlobstoreService blobstoreService;

    public ModelAndView upload(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // Get the image representation
        // ServletFileUpload upload = new ServletFileUpload();
        // FileItemIterator iter = upload.getItemIterator(request);
        // FileItemStream imageItem = iter.next();
        // InputStream imageStream = imageItem.openStream();

        String sessionId = request.getParameter("secureId");
        log.info("Uploading image for " + sessionId);

        Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
        Map.Entry<String, BlobKey> blobEntry = blobs.entrySet().iterator()
                .next();
        FlatImage flatImage = null;
        FlatImageType flatImageType = FlatImageType.valueOf(blobEntry.getKey());
//        response.setContentType("application/xml");
//        PrintWriter printWriter = response.getWriter();
//        printWriter.println("<?xml version='1.0' encoding='UTF-8'?>");
        ModelAndView res = new ModelAndView("ad/add/image");
        try {
            flatImage = flatImageService.upload(flatImageType, sessionId,
                    blobEntry.getValue());
            res.addObject("flatImageId", flatImage.getId());
//            printWriter.print("<image>" + flatImage.getId() + "</image>");
        } catch (UnsupportedImageTypeException e) {
            log.warning("Unsupported image type: " + e.getMessage());
//            printWriter.print("<error/>");
            res.addObject("unsupportedImageType", Boolean.TRUE);
        }
//        printWriter.close();
//        return null;
        res.addObject("blobstoreService", blobstoreService);
        return res;
    }
    public ModelAndView uploadUrl(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	String url = blobstoreService.createUploadUrl("/ad/add/image/upload.do");
    	response.setContentType("application/json");
    	response.getWriter().println(request.getParameter("callback") + "({'url' : '" + url + "'});");
//    	http:\/\/osa-HP:8080\/_ah\/upload\/aglvc2EtdGVzdDNyGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxhCDA
//    	response.getWriter().println("{\"url\" : \"http\"}");
    	response.getWriter().close();
    	return null;
    }
    public ModelAndView delete(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String sessionId = request.getParameter("secureId");
        FlatImageType flatImageType = FlatImageType.valueOf(request
                .getParameter("type"));
        deleteFlatImage(flatImageType, sessionId, null);
        ModelAndView res = new ModelAndView("ad/add/image");
        res.addObject("blobstoreService", blobstoreService);
        res.addObject("delete", Boolean.TRUE);
        return res;
    }

    public ModelAndView uploadedThumbnail(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        ModelAndView res = new ModelAndView("ad/add/image");
        res.addObject("blobstoreService", blobstoreService);

        String sessionId = request.getParameter("secureId");
        FlatImage flatImage = flatImageService.getUploadedImage(sessionId, FlatImageType.valueOf(request.getParameter("type")));
        if(flatImage != null){
        	res.addObject("flatImageId", flatImage.getId());
        }
        return res;
    }

    protected void deleteFlatImage(FlatImageType flatImageType, String sessionId, PersistenceManager persistenceManager){
        if(persistenceManager !=  null)
            flatImageService.delete(flatImageType, sessionId, persistenceManager);
        else
            flatImageService.delete(flatImageType, sessionId);
    }

    @Required
    public void setFlatImageService(FlatImageService flatImageService) {
        this.flatImageService = flatImageService;
    }

    @Required
    public void setBlobstoreService(BlobstoreService blobstoreService) {
        this.blobstoreService = blobstoreService;
    }
}
